//
//  ServiceViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/4.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ServiceViewController.h"
#import "SceneViewController.h"
#import "BusinessService+User.h"
#import "LoginResponseModel.h"
#import "CeneterCell.h"
//这里应该叫做senceSearchViewController
@interface ServiceViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *selectView;
@property (weak, nonatomic) IBOutlet UITextField *selectField;
@property (weak, nonatomic) IBOutlet UIView *selectBgView;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UIView *titleview;
@property (weak, nonatomic) IBOutlet UIImageView *backimg;

@end

@implementation ServiceViewController{
    NSMutableArray *service_search_list;
    NSMutableArray *typedata;
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    [self getservice_search_list]; //xhw2018-2-23加
    [self getservice_category_list];
}
-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    service_search_list = [[NSMutableArray alloc]init];
    _selectField.layer.cornerRadius = 15;
    _selectField.leftView = [[UIView alloc]initWithFrame:CGRectMake(10, 0, 10, 10)];
    _selectField.leftViewMode = UITextFieldViewModeAlways;
    _selectBgView.layer.opacity = 0.6;
    //xhw11月10号加
    _selectField.delegate = self;
    _selectField.returnKeyType = UIReturnKeySearch;
    
    _selectField.layer.borderColor = colorBG.CGColor;
    _selectField.layer.borderWidth = 0.5;
    
    _titleview.layer.borderWidth = 0.5;
    _titleview.layer.borderColor = colorBG.CGColor;
    
    _backimg.image = [ ImageService imageWithColor:[UIColor blackColor] img:_backimg.image];
    
    //xhw12月26号加:table有部分被遮挡
    _table.frame = CGRectMake(0, _titleview.frame.origin.y + _titleview.frame.size.height, SCRE_WIDTH, SCRE_HEIGHT - (_titleview.frame.origin.y + _titleview.frame.size.height));
}
-(void)getservice_search_list{
    [[BusinessService shareInstance]service_search_list:[[NSMutableDictionary alloc]init] success:^(id result) {
        service_search_list = result;
        [_table reloadData];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
-(void)getservice_category_list{
    [[BusinessService shareInstance]service_category_list:[[NSMutableDictionary alloc]init] success:^(id result) {
        [self getservice_search_list];
        typedata = result;
        for (int i=0; i<1; i++) {
            LoginResponseModel *user = [[LoginResponseModel alloc]init];
            user.img = @"";
            user.name = @"更多";
            user.id = @"0";
            [typedata addObject:user];
        }
        
    } failure:^(id result) {
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"热门搜索";
    }else{
        return @"曾经搜索";
    }
    return nil;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return service_search_list.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        CeneterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fwCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        int  s = 0;
//        int b = (SCRE_WIDTH - ((SCRE_WIDTH/6)-3)*6)/2;
        int b = (SCRE_WIDTH - ((SCRE_WIDTH/5)-3)*5)/2;
        for (int j = 0 ; j<typedata.count; j++) {
            BaseButton *btn_room = nil;
            
            //xhw12月26号改：类别一列排位5个
            if(j > 4){
                if (j%5==0) {
                    b = 0;//记录每行，当隔行重置
                    s++;
                }
//                btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/5)-3)*5)/2+b*((SCRE_WIDTH/5)-3), 0+s*(SCRE_WIDTH/5)-4+s*30, (SCRE_WIDTH/5)-4, (SCRE_WIDTH/5)-4)];
                //cw修改
                btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/5)-3)*5)/2+b*((SCRE_WIDTH/5)-3), 0+s*(SCRE_WIDTH/5)-4 + 1, (SCRE_WIDTH/5)-4, (SCRE_WIDTH/5)-4)];
            }else{
                if (typedata.count>5) {
                    btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/5)-3)*5)/2+j*((SCRE_WIDTH/5)-3), 0, (SCRE_WIDTH/5)-4, (SCRE_WIDTH/5)-4)];
                }else{
                    btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/5)-3)*5)/2+j*((SCRE_WIDTH/5)-3), 0, (SCRE_WIDTH/5)-4, (SCRE_WIDTH/5)-4)];
                }
            }

            NSLog(@"%f",btn_room.frame.origin.x);
            b++;
            btn_room.titleLabel.font = [UIFont systemFontOfSize:14];
            //            btn_room.layer.borderColor = colorGrey.CGColor;
            //            btn_room.layer.borderWidth = 1;
            btn_room.backgroundColor = [UIColor whiteColor];
            [btn_room setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            CGRect q = cell.qryView.frame;
//            q.size.height = ceilf((double)typedata.count/5)*((SCRE_WIDTH/5)-3)+s*30;
            //cw修改
            q.size.height = ceilf((double)typedata.count/5)*((SCRE_WIDTH/5)-3);
            
//            if(j > 5){
//                if (j%6==0) {
//                    b = 0;//记录每行，当隔行重置
//                    s++;
//                }
//                btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/6)-3)*6)/2+b*((SCRE_WIDTH/6)-3), 0+s*(SCRE_WIDTH/6)-4+s*30, (SCRE_WIDTH/6)-4, (SCRE_WIDTH/6)-4)];
//            }else{
//                if (typedata.count>6) {
//                    btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/6)-3)*6)/2+j*((SCRE_WIDTH/6)-3), 0, (SCRE_WIDTH/6)-4, (SCRE_WIDTH/6)-4)];
//                }else{
//                    btn_room = [[BaseButton alloc]initWithFrame:CGRectMake((SCRE_WIDTH - ((SCRE_WIDTH/6)-3)*6)/2+j*((SCRE_WIDTH/6)-3), 0, (SCRE_WIDTH/6)-4, (SCRE_WIDTH/6)-4)];
//                }
//            }
//            b++;
//            btn_room.titleLabel.font = [UIFont systemFontOfSize:14];
//            //            btn_room.layer.borderColor = colorGrey.CGColor;
//            //            btn_room.layer.borderWidth = 1;
//            btn_room.backgroundColor = [UIColor whiteColor];
//            [btn_room setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//            CGRect q = cell.qryView.frame;
//            q.size.height = ceilf((double)typedata.count/6)*((SCRE_WIDTH/6)-3)+s*30;
            cell.qryView.frame = q;
            LoginResponseModel *user = [typedata objectAtIndex:j];
//            [btn_room setTitle:user.name forState:UIControlStateNormal];
            btn_room.model = user;
            [btn_room addTarget:self action:@selector(toScene:) forControlEvents:UIControlEventTouchUpInside];
            [cell.qryView addSubview:btn_room];
            
            UIImageView *img = [[UIImageView alloc]init];
            img.bounds = CGRectMake(0, 0, 30, 30);
//            img.center = btn_room.center;
            //cw修改
            img.center = CGPointMake(btn_room.center.x, btn_room.center.y-8);
            if (user.img.length != 0) {
                [ValidateHelper setImage:user.img img:img istoux:NO];
                [cell.qryView addSubview:img];
            }else{
            }
            
            
            
//            UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(btn_room.frame.origin.x, img.frame.origin.y+img.frame.size.height, img.frame.size.width, 30)];
            UILabel *name = [[UILabel alloc] init];
            name.frame = CGRectMake(CGRectGetMinX(img.frame), CGRectGetMaxY(img.frame)-3, img.frame.size.width, 30);
            if (j==typedata.count-1) {
                [btn_room setTitle:@"更多" forState:UIControlStateNormal];
                name.hidden = YES;
            }
            name.text = user.name;
            name.font = [UIFont systemFontOfSize:13];
            name.textAlignment = NSTextAlignmentCenter;
            name.backgroundColor = [UIColor clearColor];
            [cell.qryView addSubview:name];
            
            CGRect cel = cell.frame;
            cel.size.height = q.size.height +30;
            cel.size.height = q.size.height;
            cell.frame = cel;
        }
        return cell;
    }else{
        LoginResponseModel *user = [service_search_list objectAtIndex:indexPath.row];
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"fwcell"];
        cell.textLabel.text = user.keyword;
        CGRect cel = cell.frame;
        cel.size.height = 40;
        cell.frame = cel;
        return cell;
    }
    return nil;
}


-(void)toScene:(BaseButton *)btn{
    LoginResponseModel *user = btn.model;
    
    if ([user.name isEqualToString:@"更多"]) {
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"MoreServicesVC"];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        return;
    }
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:user.id forKey:@"categoryid"];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [[BusinessService shareInstance] service_list:dic success:^(id result) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        SceneViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneVC"];
        searchResultDetailController.isview = YES;
        searchResultDetailController.isuser = NO;
        searchResultDetailController.ary = result;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LoginResponseModel *user = [service_search_list objectAtIndex:indexPath.row];
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:user.keyword forKey:@"keyword"];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [[BusinessService shareInstance] service_list:dic success:^(id result) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        SceneViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneVC"];
        searchResultDetailController.isview = YES;
        searchResultDetailController.isuser = NO;
        searchResultDetailController.ary = result;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
 }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 点击搜索框里面的搜索按钮响应事件
- (IBAction)selaction:(UIButton *)sender {
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[_selectField.text trim] forKey:@"keyword"];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [[BusinessService shareInstance] service_list:dic success:^(id result) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        SceneViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneVC"];
        searchResultDetailController.isview = YES;
        searchResultDetailController.isuser = NO;
        searchResultDetailController.ary = result;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    
    
}
#pragma mark 弹出搜索框
- (IBAction)selectAction:(UIBarButtonItem *)sender {
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[_selectField.text trim] forKey:@"keyword"];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [[BusinessService shareInstance] service_list:dic success:^(id result) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        SceneViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneVC"];
        searchResultDetailController.isview = YES;
        searchResultDetailController.isuser = NO;
        searchResultDetailController.ary = result;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];

}
#pragma mark 搜索
- (IBAction)ssAction:(UIButton *)sender {
    
}
#pragma 结果点击事件
- (IBAction)detailsAction:(UIButton *)sender {
    [self toSceneView];
}
-(void)toSceneView{
  
}
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//之前点击键盘上的搜索按钮没有反应(xhw11月10号加)
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[_selectField.text trim] forKey:@"keyword"];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [[BusinessService shareInstance] service_list:dic success:^(id result) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        SceneViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneVC"];
        searchResultDetailController.isview = YES;
        searchResultDetailController.isuser = NO;
        searchResultDetailController.ary = result;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];

    return YES;
}



@end
